package p2pcdnsim.xml;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.jdom.Document;
import org.jdom.Element;


public class RouterXMLHandler implements XMLHandler {

	private Document doc;
	private String   linkSpeed;
	private String   delay;
	private String   queue;

	public RouterXMLHandler(Document doc, String linkSpeed, String delay, String queue) {
		this.linkSpeed  = linkSpeed;
		this.delay      = delay;
		this.queue      = queue;
		this.doc        = doc;
	}
	
	@SuppressWarnings("unchecked")
	public int totalNodes() {
		Set<String> set = new HashSet<String>();
		Iterator<Element> i = this.doc.getRootElement().getChildren("Link").iterator();
		
		while (i.hasNext()) {
			Element nodesTemp = i.next();
			String nodeTo = nodesTemp.getChild("NodeTo").getText();
			String nodeFrom = nodesTemp.getChild("NodeFrom").getText();
			
			set.add(nodeTo);
			set.add(nodeFrom);
		}
		return set.size();
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	public Iterator<Element> iterator() {
		return new RouterIterator(this.doc.getRootElement().getChildren("Link").iterator());
	}
	
	private class RouterIterator implements Iterator<Element> {
		
		Iterator<Element> it;
		
		RouterIterator(Iterator<Element> it) {
			this.it = it;
		}

		@Override
		public boolean hasNext() {
			return it.hasNext();
		}

		@Override
		public Element next() {
			Element element = it.next();
			if(element.getChild("LinkSpeed").getText() == null || element.getChild("LinkSpeed").getText().equals("null"))
				element.getChild("LinkSpeed").setText(linkSpeed);
			if(element.getChild("Delay").getText() == null || element.getChild("Delay").getText().equals("null"))
				element.getChild("Delay").setText(delay);
			if(element.getChild("Queue").getText() == null || element.getChild("Queue").getText().equals("null"))
				element.getChild("Queue").setText(queue);
			return element;
		}

		@Override
		public void remove() {
			it.remove();
		}
	}

}
